const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')

const mimes = {
	'html': 'text/html;charset=utf-8',
	'css': 'text/css',
	'js': 'text/javascript',
	'png': 'image/png',
	'jpg': 'image/jpg',
	'gif': 'image/gif',
	'mp4': 'video/mp4',
	'mp3': 'audio/mpeg',
	'json': 'application/json'

}
const server = http.createServer((request, response) => {
	//只允许GET请求
	const method = request.method
	if (method !== 'GET') {
		response.statusCode = 405
		response.setHeader('content-type', 'text-html;charset=utf-8')
		response.end('<h1>405 METHOD NOT ALLOWED</h1>')
		return
	}

	const root = path.resolve(__dirname, 'static')
	const pathname = new URL(request.url, 'http://localhost:9000').pathname

	const resource = path.resolve(root, './' + pathname)

	fs.readFile(resource, (err, data) => {
		if (err) {

			console.log(err)
			switch (err.code) {
				case 'ENOENT':
					response.statusCode = 404
					response.setHeader('content-type', 'text-html;charset=utf-8')
					response.end('<h1>404 NOT FOUND</h1>')
				case 'EPERM':
					response.statusCode = 403
					response.setHeader('content-type', 'text-html;charset=utf-8')
					response.end('<h1>403 FORBIDEN</h1>')
				default:
					response.statusCode = 500
					response.setHeader('content-type', 'text-html;charset=utf-8')
					response.end('<h1>Internal Server Error</h1>')
			}
		} else {
			//设置响应类型
			const ext = path.extname(resource).slice(1)
			console.log(ext, mimes[ext])
			let type = mimes[ext];
			if (type) {

				response.setHeader('content-type', type)
			} else {
				response.setHeader('content-type', 'application/octet-stream') //如果未知类型，则直接下载
			}
			//设置MIME类型
			response.end(data)
		}
	})

})
server.listen(9000, () => {
	console.log('监听开始')
})